<script lang="ts" setup>
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { AccountApi } from '#/api';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { ElButton } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { searchByPage } from '#/api';

import { filterData, setGridApi, sortData, useColumns } from './data';

import AccountDrag from './AccountDrag.vue';

const gridRef = ref();
const currentRow = ref<null | RowVO>(null);

interface RowVO extends AccountApi.UserInfo {
  // 如果需要扩展，可以在这里添加
}
const gridOptions: VxeGridProps<RowVO> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: useColumns(),
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await searchByPage({
          pageNumber: page.currentPage,
          pageSize: page.pageSize,
          filterData,
          sortData,
        });
      },
    },
    // 添加response配置以匹配API返回格式
    response: {
      result: 'data.list', // 数据列表路径
      total: 'data.totalRow', // 总条数路径
      list: 'data.list', // 数据列表路径
    },
  },

  toolbarConfig: {
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const [DragModal, dragModalApi] = useVbenModal({
  connectedComponent: AccountDrag,
});

function openDragModal() {
  dragModalApi.open();
}
// 修改事件处理函数，符合vxe-table的CurrentRowChange类型要求
const handleCurrentChange = (params: any) => {
  // vxe-table的currentRowChange事件可能传递一个对象，其中包含currentRow属性
  // 或者直接传递行数据或null
  if (params && typeof params === 'object' && 'currentRow' in params) {
    currentRow.value = params.currentRow;
  } else {
    currentRow.value = params;
  }
  console.log('当前选中的行：', currentRow.value);
};
// 基于响应式数据判断是否有选中行
const hasCurrentRecord = () => {
  return !!currentRow.value;
};
// 创建事件处理器对象
const gridEvents: VxeGridListeners<RowVO> = {
  'currentRowChange': handleCurrentChange,
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  gridEvents,
});
// 设置gridApi引用到data.ts
setGridApi(gridApi);
</script>

<template>
  <div>
    <DragModal />
    <Page auto-content-height>
      <Grid
        ref="gridRef"
        table-title="账号列表"
        table-title-help="用户账号数据列表"
      >
        <template #toolbar-tools>
          <ElButton class="mr-2" type="primary" @click="() => gridApi.query()">
            新增
          </ElButton>
          <ElButton
            type="primary"
            :disabled="!hasCurrentRecord()"
            @click="openDragModal"
          >
            修改
          </ElButton>
        </template>
      </Grid>
    </Page>
  </div>
</template>
